/**
 * 接口统一的错误处理
 */
import axios from 'axios';
import { Message } from 'element-ui';

const errors = {};

function errorHandler(data, config = {}) {
  const { handleDefaultError } = config;
  const { message = '请求出错, 请稍后重试' } = data;

  // errors 保证同一个错误只弹出一次弹框
  if (handleDefaultError !== false && !errors[message]) {
    Message.error({
      showClose: true,
      message: message,
      duration: 3000,
      onClose: () => {
        errors[message] = false;
      },
    });

    errors[message] = true;
  }
}

export default instance => {
  // Add a response interceptor
  instance.interceptors.response.use(
    response => response,
    error => {
      const { response, config } = error;
      const data = {
        error,
        message: '',
      };

      if (response) {
        data.status = response.status;
        data.message = response.data && response.data.message;
      } else {
        data.message = error.message;
      }

      // 如果是重复请求，不弹出错误
      if (!axios.isCancel(error)) {
        errorHandler(data, config);
      }

      return Promise.reject(error);
    }
  );
};
